package com.rad.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rad.dao.ImageDaoITF;
import com.rad.dao.impl.ImageDaoImpl;

public class ImageViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ImageDaoITF imageDao = new ImageDaoImpl();
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ImageViewServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if ("showcategory".equals(method)) {
			showImageCategory(request, response);
		} else if ("showimg".equals(method)) {
			showImage(request, response);
		} else if ("shownextimg".equals(method)) {
			showNextImage(request, response);
		} else if("showcityplan".equals(method)){
			showCityPlan(request, response);
		} else if("goupdatedescription".equals(method)) {
			goUpdateDescription(request, response);
		} else if("updatedescription".equals(method)) {
			updateDescription(request, response);
		} else if("deleteimg".equals(method)) {
			deleteImage(request, response);
		}
	}

	private void showImageCategory(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String defaultImageUrl = "assetsImg\\noimgs.jpg";
		String zdid = request.getParameter("zdid");
		zdid = StringToHash(zdid);
		String root = request.getRealPath("/");

		String[] categoryNames = new String[] { "yuanwaisilin",
				"yuanneisizhi", "shineiqingkuang", "qita" };

		for (String categoryName : categoryNames) {
			File zhengjian = new File(root + "assetsImg\\" + zdid + "\\"
					+ categoryName);
			String[] names = zhengjian.list();
			String categoryUrl = defaultImageUrl;
			int categoryImgCount = 0;
			if (names != null && names.length > 0) {
				categoryUrl = "assetsImg\\" + zdid + "\\" + categoryName
						+ "\\" + names[0];
				categoryImgCount = names.length;
				for (String name : names) {
					if (name.toLowerCase().equals("0.jpg")) {
						categoryUrl = "assetsImg\\" + zdid + "\\"
								+ categoryName + "\\0.jpg";
						categoryImgCount = names.length - 1;
						break;
					}
				}
			}
			request.setAttribute(categoryName + "Url", categoryUrl);
			request.setAttribute(categoryName + "ImgCount",
					categoryImgCount);
		}
		request.setAttribute("zdid", zdid);
		request.getRequestDispatcher("/imagecategory.jsp").forward(request,
				response);
	}

	@SuppressWarnings("deprecation")
	private void showImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String zdid = request.getParameter("zdid");
		String categoryName = request.getParameter("category");

		String root = request.getRealPath("/");
		String imageFolderPath = root + "assetsImg\\" + zdid + "\\"
				+ categoryName;
		File zhengjian = new File(imageFolderPath);
		String[] names = zhengjian.list();
		if (names != null && names.length > 0) {
			List<String> realImageNames = new ArrayList<String>();
			for (String name : names) {
				if (!name.toLowerCase().equals("0.jpg")) {
					realImageNames.add(name);
				}
			}

			if (realImageNames.size() > 0) {

				request.getSession().setAttribute("imageFolderPath",
						imageFolderPath);
				request.getSession().setAttribute("imageIndex", 0);

				String imageToDisplay = "assetsImg\\" + zdid + "\\"	+ categoryName + "\\" + realImageNames.get(0);
				request.setAttribute("imageUrl", imageToDisplay);
				
				String imageTicket = zdid + categoryName + realImageNames.get(0);
				request.setAttribute("imageTicket", imageTicket);
				
				String imageDescription = imageDao.getImageinfo(imageTicket);
				request.setAttribute("imageDescription", imageDescription);
				request.getRequestDispatcher("/showimage.jsp").forward(request,
						response);
			}
		}
	}

	@SuppressWarnings("deprecation")
	private void showNextImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String imageFolderPath = (String) request.getSession().getAttribute(
				"imageFolderPath");
		int imageIndex = (Integer) request.getSession().getAttribute(
				"imageIndex");

		File zhengjian = new File(imageFolderPath);
		String[] names = zhengjian.list();

		List<String> realImageNames = new ArrayList<String>();
		for (String name : names) {
			if (!name.toLowerCase().equals("0.jpg")) {
				realImageNames.add(name);
			}
		}

		if (realImageNames.size() > 0) {
			int newIndex = 0;
			if (imageIndex < realImageNames.size() - 1) {
				newIndex = imageIndex + 1;
			}
			request.getSession().setAttribute("imageIndex", newIndex);
			
			String root = request.getRealPath("/");
			
			String imageToDisplay = imageFolderPath.substring(root.length()) + "\\"
					+ realImageNames.get(newIndex);
			request.setAttribute("imageUrl", imageToDisplay);
			
			String imageTicket = imageToDisplay.substring(10).replace("\\", "");
			request.setAttribute("imageTicket", imageTicket);
			
			String imageDescription = imageDao.getImageinfo(imageTicket);
			request.setAttribute("imageDescription", imageDescription);
			
			request.getRequestDispatcher("/showimage.jsp").forward(request,
					response);
		}
	}
	
	private void showCityPlan(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String cityName = request.getParameter("cname");
		String imageUrl = "assetsImg\\" + cityName + ".jpg";
		
		request.setAttribute("imageUrl", imageUrl);
		request.getRequestDispatcher("/showcityplan.jsp").forward(request, response);
	}

	public static String StringToHash(String str) {
		Integer i  = str.hashCode();
		if(i < 0){				
			i = (-1) * i;
		}
		return i.toString();
	}
	
	private void goUpdateDescription(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String imageTicket = request.getParameter("imageticket");
		request.setAttribute("imageTicket", imageTicket);
		request.getRequestDispatcher("/updateImageDesc.jsp").forward(request,
				response);
	}
	
	private void updateDescription(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String imageTicket = request.getParameter("imageTicket");
		String newDescription = request.getParameter("newDescription");
		imageDao.saveImageinfo(imageTicket, newDescription);
		
		response.sendRedirect("blank.jsp");	
	}
	
	private void deleteImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String imageFolderPath = (String) request.getSession().getAttribute(
				"imageFolderPath");
		int imageIndex = (Integer) request.getSession().getAttribute(
				"imageIndex");

		File zhengjian = new File(imageFolderPath);
		String[] names = zhengjian.list();

		List<String> realImageNames = new ArrayList<String>();
		for (String name : names) {
			if (!name.toLowerCase().equals("0.jpg")) {
				realImageNames.add(name);
			}
		}

		int realImageCount = realImageNames.size();
		if (realImageCount > 0) {
			//Delete the image file.
			if(imageIndex < realImageCount) {
				String filePathToDelete = imageFolderPath + "\\" + realImageNames.get(imageIndex);
				File imageFileToDelete = new File(filePathToDelete);
				if(imageFileToDelete.exists()) {
					imageFileToDelete.delete();
					realImageNames.remove(imageIndex);
					
					//If this is the last image, delete the preview image.
					if(realImageNames.size() == 0) {
						String previewFilePath = imageFolderPath + "\\0.jpg";
						File previewFile = new File(previewFilePath);
						if(previewFile.exists()) {
							previewFile.delete();
						}
					}
					else	//Re-create the category preview image. Because maybe the previous preview is's source image may have been deleted already.
					{
						try {
							String lastImagePath = imageFolderPath + "\\" + realImageNames.get(realImageNames.size() - 1);
							String destPath = imageFolderPath + "\\" + "0.jpg";
							ImageUploadServlet.createPreviews(lastImagePath, destPath, 160, 120);
						}
						catch(Exception ex){
							ex.printStackTrace();
						}
					}
				}
			}
			
			String imageToDisplay = null, imageTicket = null, imageDescription = null;
			if(realImageNames.size() > 0) {	//If there is images left
				//Change the index.
				int newIndex = imageIndex;
				if (imageIndex == realImageCount - 1) {
					newIndex = 0;
				}
				request.getSession().setAttribute("imageIndex", newIndex);
				
				String root = request.getRealPath("/");
				
				imageToDisplay = imageFolderPath.substring(root.length()) + "\\"
						+ realImageNames.get(newIndex);
				imageTicket = imageToDisplay.substring(10).replace("\\", "");
				imageDescription = imageDao.getImageinfo(imageTicket);
				
				request.setAttribute("imageUrl", imageToDisplay);
								
				request.setAttribute("imageTicket", imageTicket);
								
				request.setAttribute("imageDescription", imageDescription);
				
				request.getRequestDispatcher("/showimage.jsp").forward(request,
						response);
			}
		}
	}
}
